package com.shuzhi.stationarysource.modules.job.task;


import com.alibaba.fastjson.JSON;
import com.shuzhi.stationarysource.modules.job.domain.FixedSource;
import com.shuzhi.stationarysource.modules.job.service.FixedSourceService;
import com.shuzhi.stationarysource.modules.job.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


import java.io.IOException;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ServiceInterface
 * @Description ServiceInterface
 * @Author 孙峰
 * @Date 2020/3/10 10:32
 * @Version 1.0
 */
@Slf4j
@Component
public class DataService{

    private final FixedSourceService fixedSourceService;

    public DataService(FixedSourceService fixedSourceService) {
        this.fixedSourceService = fixedSourceService;
    }

    /**
     * 查询行业代码及名称
     */
    public static void findTradeCodeAndName() {
        try {
            HttpUtils.getMethod("http://10.100.244.160:8088/service/serviceinterface/search/run.action?interfaceId=6D4F2EA02B9E4398A669ED70FA05BD01");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 查询行政区代码以及名称
     */
    public static void findRegionCodeAndName() {
        try {
            HttpUtils.getMethod("http://10.100.244.160:8088/service/serviceinterface/search/run.action?interfaceId=0BDEA776221B41CF8A25D75478EBCC16");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 获取固定点源全部数据
     */
    public void getDockData() {
    // 请求url--动态pageNum
        String url = "http://10.100.244.160:8088/service/serviceinterface/search/run.action?interfaceId=6F791BC64C4045ECB7C6F77DFA8CDF76&token=9b7202888fdf1de45d415387aae233e9&CODE_REGION=370000&pageSize=1000&pageNum=";
    //可以根据返回的数据做一个日志分析
        List<FixedSource> list = null;
        String JsonStr = "";
        try {
            JsonStr = HttpUtils.getMethod(url + 1);

            Map<String, Object> map = (Map<String, Object>) JSON.parse(JsonStr);
            Map<String, Object> head = (Map<String, Object>) map.get("head");
            Map<String, Object> pageInfo = (Map<String, Object>) head.get("pageInfo");
            int total = (int)  pageInfo.get("total");
            int pages = (int) pageInfo.get("pages");
            for (int i = 1; i <= pages; i++) {
                list = JSON.parseArray(JSON.toJSONString(map.get("data")), FixedSource.class);
                if (list != null) {

                    fixedSourceService.savaAll(list);
                } else {
                    log.info("存储失败");
                }
                JsonStr = HttpUtils.getMethod(url + (i + 1));
                map = (Map<String, Object>) JSON.parse(JsonStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("数据拉去执行完毕");
    }


}
